package com.linksoul;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
@SpringBootApplication
@EnableAspectJAutoProxy
@MapperScan("com.linksoul.mapper")
@ComponentScan(basePackages = {"com.linksoul", "com.linksoul.config"})
public class LinkSoulApplication {

    public static void main(String[] args) {
        SpringApplication.run(LinkSoulApplication.class, args);
    }

    @Bean
    public CommandLineRunner checkDataSources(DataSource linkSoulDataSource, DataSource soulMbtiDataSource) {
        return args -> {
            // 检查 link_soul 数据源连接
            testDataSourceConnection(linkSoulDataSource, "link-soul");

            // 检查 soul_mbti 数据源连接
            testDataSourceConnection(soulMbtiDataSource, "soul-mbti");
        };
    }

    private void testDataSourceConnection(DataSource dataSource, String dataSourceName) {
        try (Connection connection = dataSource.getConnection()) {
            log.info("✅ 数据源 [{}] 连接成功！URL: {}", dataSourceName, connection.getMetaData().getURL());
        } catch (SQLException e) {
            log.error("❌ 数据源 [{}] 连接失败！错误信息: {}", dataSourceName, e.getMessage());
            throw new RuntimeException("数据源连接失败: " + dataSourceName, e);
        }
    }
}